package com.campus.task;

import com.campus.common.RedisCache;
import com.campus.entity.PostDetailDTO;
import com.campus.mapper.HotRankingsMapper;
import com.campus.service.HotRankingService;
import com.campus.service.impl.HotRankingServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@Component
public class ScheduledTasks {
    
    @Autowired
    private HotRankingsMapper hotRankingsMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HotRankingService hotRankingService;
    
    /**
     * 定时更新热力榜数据到Redis ZSet
     * 每30分钟执行一次
     */
    @Scheduled(fixedRate = 30 * 60 * 1000) // 30分钟
    public void updateHotRankingZSet() {
        try {
            // 定义时间范围
            List<String> dateRanges = Arrays.asList("today", "week", "month");

            // 获取当前时间用于日志
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.println("[" + currentTime + "] 开始更新热力榜Redis ZSet数据");

            for (String date : dateRanges) {
                // 查询该时间范围内的热力帖子（限制100条）
                List<PostDetailDTO> hotPosts = hotRankingsMapper.getHotPostsByDate(100, date);

                if (hotPosts != null && !hotPosts.isEmpty()) {
                    // 删除旧的ZSet数据
                    String zsetKey = RedisCache.HOT_RANKING_ZSET_KEY_PREFIX + date;
                    stringRedisTemplate.delete(zsetKey);

                    // 将新的数据存入Redis ZSet
                    ((HotRankingServiceImpl) hotRankingService).saveHotPostsToRedis(hotPosts, date);

                    // 将帖子详情也缓存到Redis中
                    ((HotRankingServiceImpl) hotRankingService).savePostDetailsToRedis(hotPosts);

                    System.out.println("[" + currentTime + "] 更新" + date + "热力榜数据完成，共" + hotPosts.size() + "条记录");
                }
            }

            System.out.println("[" + currentTime + "] 热力榜Redis ZSet数据更新完成");
        } catch (Exception e) {
            System.err.println("更新热力榜Redis ZSet数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}